/**
 * 外部模块加载器
 * 支持从任意路径动态加载模块
 */

export interface ExternalModuleConfig {
  loadExternalModules: boolean;
  externalMoudlePath: string;
}

export class ExternalModuleLoader {
  private static instance: ExternalModuleLoader;
  private config: ExternalModuleConfig | null = null;

  static getInstance(): ExternalModuleLoader {
    if (!ExternalModuleLoader.instance) {
      ExternalModuleLoader.instance = new ExternalModuleLoader();
    }
    return ExternalModuleLoader.instance;
  }

  async loadConfig(): Promise<ExternalModuleConfig> {
    if (this.config) {
      return this.config;
    }

    try {
      const response = await fetch('/load-modules-config.json');
      if (!response.ok) {
        throw new Error(`配置文件请求失败，状态码: ${response.status}`);
      }
      this.config = await response.json();
      return this.config;
    } catch (error) {
      console.error('配置文件异常，使用默认配置：', error);
      this.config = {
        loadExternalModules: false,
        externalMoudlePath: '../modules/'
      };
      return this.config;
    }
  }

  async loadModule(moduleName: string): Promise<any> {
    const config = await this.loadConfig();
    
    if (config.loadExternalModules && config.externalMoudlePath) {
      return this.loadFromExternalPath(config.externalMoudlePath, moduleName);
    } else {
      return this.loadFromInternalPath(moduleName);
    }
  }

  private async loadFromExternalPath(externalPath: string, moduleName: string): Promise<any> {
    // 处理路径格式
    const normalizedPath = externalPath.replace(/\\/g, '/');
    
    // 开发环境：使用文件系统路径
    if (import.meta.env.DEV) {
      const modulePath = `${normalizedPath}/${moduleName}/${moduleName}.js`;
      return import(modulePath);
    }
    
    // 生产环境：使用相对路径或网络路径
    const moduleUrl = `${normalizedPath}/${moduleName}/${moduleName}.js`;
    
    // 动态加载脚本
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = moduleUrl;
      script.onload = () => {
        // 假设模块挂载在全局变量上
        const module = (window as any)[`${moduleName}Module`];
        if (module) {
          resolve(module);
        } else {
          reject(new Error(`模块 ${moduleName} 加载成功但未找到导出内容`));
        }
      };
      script.onerror = () => reject(new Error(`模块 ${moduleName} 加载失败`));
      document.head.appendChild(script);
    });
  }

  private async loadFromInternalPath(moduleName: string): Promise<any> {
    return import(`@/modules/${moduleName}/${moduleName}.js`);
  }

  async loadStyles(moduleName: string, config: ExternalModuleConfig): Promise<void> {
    try {
      let stylePath: string;
      
      if (config.loadExternalModules && config.externalMoudlePath) {
        const externalPath = config.externalMoudlePath.replace(/\\/g, '/');
        stylePath = `${externalPath}/${moduleName}/assets/style.css`;
      } else {
        stylePath = `@/modules/${moduleName}/assets/style.css`;
      }

      // 动态加载样式
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = stylePath;
      document.head.appendChild(link);
    } catch (error) {
      console.warn('样式文件加载失败:', error);
    }
  }
}

// 创建全局模块加载器实例
export const externalModuleLoader = ExternalModuleLoader.getInstance();